package com.cysyz.web.modules.base.permission.filter;

import com.cysyz.web.modules.base.permission.support.PermissionContentType;
import com.cysyz.web.modules.base.support.SysConstants;

import javax.servlet.*;
import javax.servlet.annotation.WebFilter;
import java.io.IOException;

/**
 * Created by cuiyong on 15/7/2.
 */
@WebFilter("/*")
public class PermissionResponseFilter implements Filter{

    @Override
    public void init(FilterConfig filterConfig) throws ServletException {

    }

    @Override
    public void doFilter(ServletRequest request, ServletResponse response, FilterChain chain) throws IOException, ServletException {

        chain.doFilter(request, response);

        String contentType = response.getContentType();

        if (contentType != null) {
            PermissionContentType permissionContentType = null;

            boolean permissionCheckFail = false;
            if (contentType.equals(PermissionContentType.LOGIN_CHECK_FAIL.toString())) {
                permissionContentType = PermissionContentType.LOGIN_CHECK_FAIL;
                permissionCheckFail = true;
            } else if (contentType.equals(PermissionContentType.PERMISSION_CHECK_FAIL.toString())) {
                permissionContentType = PermissionContentType.PERMISSION_CHECK_FAIL;
                permissionCheckFail = true;
            }

            if (permissionCheckFail) {
                response.setContentType("text/html;charset=UTF-8");
                response.setCharacterEncoding(SysConstants.Charset.UTF_8);
                response.getWriter().print(permissionContentType.getResponseBody());
            }
        }
    }

    @Override
    public void destroy() {

    }
}
